# -*- coding:utf-8 -*-
"""

Created by Line on 2017/5/5.
"""

import os, sys, time, platform
from os.path import *

from Tkinter import *

# from kbtools import *
import Image

__auther__ = 'line'

# 数据格式 元表
SPINE_STRUCT = ('png_path', 'format', 'filter', 'size_wid', 'size_hei', 'repeat')


class AntiAtlas:
    '''
    @ATLAS_STRUCT,pnglist
    girl.png
    size: 1017,510
    format: RGBA8888
    filter: Linear,Linear
    repeat: none
    attment
        rotate: false
        xy: 541, 159
        size: 37, 23
        orig: 39, 25
        offset: 1, 1
        index: -1
    '''

    def __init__(self, filename):
        self.atlasFileName = filename

        self.atlasBasePath = os.path.dirname(filename)
        self.atlasName = os.path.basename(filename)
        self.atlasName = self.atlasName[:-len(".atlas")]

        self.resourcePath = ""
        self.flag = False

        self.imgFileName = ""

    def parse(self):
        atlas_info = {
            "pngFileName": "",
            "size": (0, 0),
            "format": "RGBA8888",
            "filter": ("Linear", "Linear"),
            "repeat": "none",
        }

        f = open(self.atlasFileName, 'r')

        # 读取头
        while True:
            line = f.readline()
            # 去除空格
            line = ''.join(line.split())
            if not len(line):
                continue
            if line.endswith(".png"):
                line = line.replace("/", os.path.sep)
                atlas_info["pngFileName"] = line
                continue
            keyValue = line.split(':')
            if len(keyValue) == 2:
                key = keyValue[0].strip()
                value = keyValue[1].strip()
                atlas_info[key] = value
                if key == 'repeat':
                    break

        print("=============================================")
        print atlas_info

        self.imgFileName = "%s%s%s" % (self.atlasBasePath, os.path.sep, atlas_info["pngFileName"])
        self.img = Image.open(self.imgFileName)

        while True:
            line = f.readline()
            if not line:
                break
            line = ''.join(line.split())
            if not len(line):
                continue
            smallFileName = line.replace("/", os.path.sep) + ".png"
            smallImageInfo = {}
            for i in range(6):
                line = f.readline()
                if not line:
                    break
                line = ''.join(line.split())
                keyValue = line.split(':')
                if len(keyValue) == 2:
                    smallImageInfo[keyValue[0]] = keyValue[1]

            print("---------------------------------------------")
            print smallImageInfo
            if not smallImageInfo.get("xy"):
                break

            # 截取小图
            x, y = smallImageInfo.get("xy").split(",")
            x = int(x)
            y = int(y)
            w, h = smallImageInfo.get("size").split(",")
            w = int(w)
            h = int(h)
            isRoate = smallImageInfo.get("rotate") == "true"

            if isRoate:
                region = (x, y, x + h, y + w)
            else:
                region = (x, y, x + w, y + h)

            # 裁切图片
            rect_on_big = self.img.crop(region)
            if isRoate:
                rect_on_big = rect_on_big.rotate(270)

            smallImgSize = [w, h]
            result_image = Image.new('RGBA', smallImgSize, (0, 0, 0, 0))
            result_box = (0, 0, w, h)
            # if isRoate:
            # 	result_box = (0, 0, h, w)
            # else:
            # 	result_box = (0, 0, w, h)
            result_image.paste(rect_on_big, result_box, mask=0)

            exportFileName = "atlas_export%s%s%s%s" % (os.path.sep, self.atlasName, os.path.sep, smallFileName)
            saveFilename = os.path.join(self.atlasBasePath, exportFileName)
            savePath = os.path.dirname(saveFilename)
            if not os.path.exists(savePath):
                os.makedirs(savePath)
            if os.path.exists(saveFilename):
                os.remove(saveFilename)

            result_image.save(saveFilename)
            pass


def unpak_dir_file(path):
    for dirpath, dirs, files in os.walk(path):
        for file in files:
            abs_path = os.path.join(dirpath, file)
            postfix = os.path.splitext(abs_path)[1]
            if postfix == ".atlas":
                a_len = len(".atlas")
                print(abs_path)
                anti = AntiAtlas(abs_path)
                anti.parse()


if __name__ == '__main__':
    unpak_dir_file("C:\\Users\\Line\\Desktop\\logs\\update1.302_1.311\\res")

    # unpak_dir_file("C:\\Users\\Line\\Desktop\\logs\\update1.302_1.311\\res\\spineAni")

    # anti = AntiAtlas("C:\\Users\\Line\\Desktop\\logs\\update1.302_1.311\\res\\spineAni\\loading.atlas")
    # anti.parse()

    # anti = AntiAtlas("C:\\Users\\Line\\Desktop\\logs\\update1.302_1.311\\res\\GameRes\\spine\\gameAnim\\dtGameAnim.atlas")
    # anti.parse()

    pass
